﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SUPan
{
    class DataManager
    {
        Dictionary<string, FileInfoRecord> dic_name_info;
        List<FileInfoRecord> infos;
        FileInfosRecord records = null;
        const string RecordFilename = "Record.json";
        string record_full_path;

        public List<FileInfoRecord> Infos {
            get {
                return this.infos;
            }
        }

        public void Init() {

            string exe_path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            record_full_path = Path.Combine(exe_path, RecordFilename);

            LoadReco();

            dic_name_info = new Dictionary<string, FileInfoRecord>();
            infos = records.infos;
            for (int i = 0; i < infos.Count; i++)
            {
                if (!dic_name_info.ContainsKey(infos[i].name)) {
                    dic_name_info.Add(infos[i].name, infos[i]);
                }
            }
        }

        public bool AddRecoInfo(FileInfoRecord reco) {
            if (!dic_name_info.ContainsKey(reco.name))
            {
                dic_name_info.Add(reco.name, reco);
                infos.Add(reco);
                SaveReco();
                return true;
            }
            return false;
        }

        public bool DelRecoInfo(FileInfoRecord reco) {
            if (dic_name_info.ContainsKey(reco.name))
            {
                dic_name_info.Remove(reco.name);
                infos.Remove(reco);
                SaveReco();
                return true;
            }
            return false;
        }

        private void LoadReco() {
            //读取
            if (!File.Exists(record_full_path))
            {
                records = CreateDefaultRecordfile(record_full_path);
            }
            else
            {
                string data = File.ReadAllText(record_full_path);
                records = JsonConvert.DeserializeObject<FileInfosRecord>(data);
            }
        }

        private void SaveReco() {
            //写入
            string finalStr = JsonConvert.SerializeObject(records, Formatting.Indented);
            File.WriteAllText(record_full_path, finalStr);
        }

        private FileInfosRecord CreateDefaultRecordfile(string path)
        {
            FileInfosRecord records = new FileInfosRecord();
            string str = JsonConvert.SerializeObject(records);
            File.WriteAllText(path, str);
            return records;
        }

    }

    class FileInfosRecord
    {
        public List<FileInfoRecord> infos = new List<FileInfoRecord>();
    }

    class FileInfoRecord
    {
        public string name;
        public string fullpath;
    }

}
